package com.ooono.factorytest.items;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.GnssStatus;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.ooono.factorytest.R;
import com.ooono.factorytest.base.BaseActivity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import mcs8.mdm.PolicyManager;

public class GpsTestActivity extends BaseActivity {

    private static final String TAG = "GpsTestActivity";

    public static final String KEY = "gps";

    private TextView gpsConnectTv;
    private TextView gpsSatellitesCountTv;
    private TextView availableSatellitesCountTv;

    private String beidou = "1";

    GpsAdapter mGpsAdapter;
    // 卫星信号
    List<SatellitesLiteInfo> mAdapterData = new ArrayList<>();

    @Override
    public int getTestTitle() {
        return R.string.gps_test_prompt;
    }

    @Override
    public String getTestKey() {
        return KEY;
    }

    @Override
    public int getContentLayout() {
        return R.layout.content_gps_test;
    }

    @Override
    public void initViews() {
        String beidouChip = PolicyManager.getSystemProperties("ro.beidou.chip", "0");
        if ("1".equals(beidouChip)) {
            middleBtn.setVisibility(View.VISIBLE);
        }
        middleBtn.setOnClickListener(v -> {
            // 开关北头
            if ("1".equals(beidou)) {
                beidou = "0";
                middleBtn.setText(R.string.gps_test_open);
            } else {
                beidou = "1";
                middleBtn.setText(R.string.gps_test_close);
            }
            PolicyManager.setDriveNodeValue("/sys/class/leds/alermled/huada_gps", beidou);
        });

        gpsConnectTv = findViewById(R.id.tv_gps_connect);
        gpsSatellitesCountTv = findViewById(R.id.tv_gps_satellites_count);
        availableSatellitesCountTv = findViewById(R.id.tv_available_satellites_count);
        ListView gpsSnrListLv = findViewById(R.id.lv_gps_snr_list);
        // listview :显示GPS检测列表
        mGpsAdapter = new GpsAdapter(this, R.layout.gps_test_list_item);
        gpsSnrListLv.setAdapter(mGpsAdapter);
    }

    @SuppressLint({"SetTextI18n", "SimpleDateFormat"})
    @Override
    protected void onResume() {
        super.onResume();
        beidou = PolicyManager.getDriveNodeValue("/sys/class/leds/alermled/huada_gps");
        if ("1".equals(beidou)) {
            middleBtn.setText(R.string.gps_test_close);
        } else {
            middleBtn.setText(R.string.gps_test_open);
        }
        boolean enabled = Settings.Secure.isLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER);
        if (!enabled) {
            Settings.Secure.setLocationProviderEnabled(getContentResolver(), LocationManager.GPS_PROVIDER, true);
        }

        LocationManager mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Log.d(TAG, "mLocationManager:" + mLocationManager);
        if (mLocationManager != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 5, location -> {
                Log.d(TAG, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "当前位置 longitude : " + location.getLongitude() +
                        "latitude : " + location.getLatitude());
            });
            gpsConnectTv.setText(R.string.gps_test_text_default);
            int mSatellitesCount = 0;
            gpsSatellitesCountTv.setText(getString(R.string.gps_test_search_result_tip) + mSatellitesCount);
        } else {
            gpsConnectTv.setText(R.string.gps_test_get_location_fail);
        }
        assert mLocationManager != null;
        mLocationManager.registerGnssStatusCallback(new GnssStatus.Callback() {

            @Override
            public void onSatelliteStatusChanged(@NonNull GnssStatus status) {
                super.onSatelliteStatusChanged(status);

                int satelliteCount = status.getSatelliteCount();

                int cn0DbHz30SatelliteCount = 0;
                int cn0DbHz37SatelliteCount = 0;
                for (int i = 0; i < satelliteCount; i++) {
                    float cn0DbHz = status.getCn0DbHz(i);
                    SatellitesLiteInfo satellitesLiteInfo = new SatellitesLiteInfo();
                    satellitesLiteInfo.svid = status.getSvid(i);
                    satellitesLiteInfo.elevationDegrees = status.getElevationDegrees(i);
                    satellitesLiteInfo.constellationType = status.getConstellationType(i);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        satellitesLiteInfo.carrierFrequencyHz = status.getCarrierFrequencyHz(i);
                        satellitesLiteInfo.basebandCn0DbHz = status.getBasebandCn0DbHz(i);
                    }
                    satellitesLiteInfo.azimuthDegrees = status.getAzimuthDegrees(i);
                    if (cn0DbHz >= 30) {
                        cn0DbHz30SatelliteCount++;
                    }
                    if (cn0DbHz >= 37) {
                        cn0DbHz37SatelliteCount++;
                    }
                    mAdapterData.add(satellitesLiteInfo);
                }
                gpsSatellitesCountTv.setText("搜索到总卫星数 : " + satelliteCount);
                availableSatellitesCountTv.setText("cno >37 的卫星数 ：" + cn0DbHz37SatelliteCount + "\ncno >30 的卫星数 ：" + cn0DbHz30SatelliteCount);
                mGpsAdapter.notifyDataSetChanged();
            }
        });
    }

    class SatellitesLiteInfo {
        int svid;
        float elevationDegrees;
        int constellationType;
        float carrierFrequencyHz;
        float basebandCn0DbHz;
        float azimuthDegrees;
    }

    private class GpsAdapter extends BaseAdapter {
        private final int sourceId;
        private final LayoutInflater inflater;

        public GpsAdapter(Context context, int sourceId) {
            inflater = LayoutInflater.from(context);
            this.sourceId = sourceId;
        }

        @Override
        public int getCount() {
            return mAdapterData.size();
        }

        @Override
        public Object getItem(int position) {
            return mAdapterData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @SuppressLint("SetTextI18n")
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = inflater.inflate(sourceId, null);
                holder = new ViewHolder();
                holder.listItemSvidTv = convertView.findViewById(R.id.gps_test_list_item_svid);
                holder.listItemElevationDegrees = convertView.findViewById(R.id.gps_test_list_item_elevation_degrees);
                holder.listItemCarrierFrequencyHz = convertView.findViewById(R.id.gps_test_list_item_carrier_frequency_hz);
                holder.listItemSnrValue = convertView.findViewById(R.id.gps_test_list_item_snr_value);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.listItemSvidTv.setText(mAdapterData.get(position).svid + "");
            holder.listItemElevationDegrees.setText(mAdapterData.get(position).elevationDegrees + "");
            holder.listItemCarrierFrequencyHz.setText(mAdapterData.get(position).carrierFrequencyHz + "");
            holder.listItemSnrValue.setText(mAdapterData.get(position).basebandCn0DbHz + "");

            return convertView;
        }

        private final class ViewHolder {
            TextView listItemSvidTv;
            TextView listItemElevationDegrees;
            TextView listItemCarrierFrequencyHz;
            TextView listItemSnrValue;
        }
    }

}